home *** CD-ROM | disk | FTP | other *** search
/ Visual Cafe 3 / Visual Cafe 3.ISO / Vcafe / Sample.bin / SampleTree.java < prev    next >
Text File  |  1998-06-30  |  13KB  |  400 lines

  1. /*
  2.  * @(#)SampleTree.java    1.11 98/02/23
  3.  *
  4.  * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved.
  5.  *
  6.  * This software is the confidential and proprietary information of Sun
  7.  * Microsystems, Inc. ("Confidential Information").  You shall not
  8.  * disclose such Confidential Information and shall use it only in
  9.  * accordance with the terms of the license agreement you entered into
  10.  * with Sun.
  11.  *
  12.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
  13.  * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  14.  * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  15.  * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
  16.  * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
  17.  * THIS SOFTWARE OR ITS DERIVATIVES.
  18.  *
  19.  */
  20.  
  21. import com.sun.java.swing.*;
  22. import com.sun.java.swing.event.*;
  23. import java.awt.BorderLayout;
  24. import java.awt.Color;
  25. import java.awt.Dimension;
  26. import java.awt.FlowLayout;
  27. import java.awt.event.ActionEvent;
  28. import java.awt.event.ActionListener;
  29. import java.awt.event.WindowAdapter;
  30. import java.awt.event.WindowEvent;
  31. import com.sun.java.swing.tree.*;
  32.  
  33. /**
  34.   * A demo for illustrating how to do different things with JTree.
  35.   * The data that this displays is rather boring, that is each node will
  36.   * have 7 children that have random names based on the fonts.  Each node
  37.   * is then drawn with that font and in a different color.
  38.   * While the data isn't interesting the example illustrates a number
  39.   * of things:
  40.   *
  41.   * For an example of dynamicaly loading children refer to DynamicTreeNode.
  42.   * For an example of adding/removing/inserting/reloading refer to the inner
  43.   *     classes of this class, AddAction, RemovAction, InsertAction and
  44.   *     ReloadAction.
  45.   * For an example of creating your own cell renderer refer to
  46.   *     SampleTreeCellRenderer.
  47.   * For an example of subclassing JTreeModel for editing refer to
  48.   *     SampleTreeModel.
  49.   *
  50.   * @version 1.11 02/23/98
  51.   * @author Scott Violet
  52.   */
  53.  
  54. public class SampleTree
  55. {
  56.     /** Window for showing Tree. */
  57.     protected JFrame            frame;
  58.     /** Tree used for the example. */
  59.     protected JTree             tree;
  60.     /** Tree model. */
  61.     protected DefaultTreeModel        treeModel;
  62.  
  63.     /**
  64.       * Constructs a new instance of SampleTree.
  65.       */
  66.     public SampleTree() {
  67.     // Force SampleTree to come up in the Cross Platform L&F
  68.     try {
  69.         UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
  70.         // If you want the System L&F instead, comment out the above line and
  71.         // uncomment the following:
  72.         // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  73.     } catch (Exception exc) {
  74.         System.err.println("Error loading L&F: " + exc);
  75.     }
  76.  
  77.  
  78.     JMenuBar         menuBar = constructMenuBar();
  79.     JPanel           panel = new JPanel(true);
  80.  
  81.     frame = new JFrame("SampleTree");
  82.     frame.getContentPane().add("Center", panel);
  83.     frame.setJMenuBar(menuBar);
  84.     frame.setBackground(Color.lightGray);
  85.  
  86.     /* Create the JTreeModel. */
  87.     DefaultMutableTreeNode root = createNewNode("Root");
  88.     treeModel = new SampleTreeModel(root);
  89.  
  90.     /* Create the tree. */
  91.     tree = new JTree(treeModel);
  92.  
  93.     /* Enable tool tips for the tree, without this tool tips will not
  94.        be picked up. */
  95.     ToolTipManager.sharedInstance().registerComponent(tree);
  96.  
  97.     /* Make the tree use an instance of SampleTreeCellRenderer for
  98.        drawing. */
  99.     tree.setCellRenderer(new SampleTreeCellRenderer());
  100.  
  101.     /* Make tree ask for the height of each row. */
  102.     tree.setRowHeight(-1);
  103.  
  104.     /* Put the Tree in a scroller. */
  105.     JScrollPane        sp = new JScrollPane();
  106.     sp.setPreferredSize(new Dimension(300, 300));
  107.     sp.getViewport().add(tree);
  108.  
  109.     /* And show it. */
  110.     panel.setLayout(new BorderLayout());
  111.     panel.add("Center", sp);
  112.     panel.add("South", constructOptionsPanel());
  113.  
  114.     frame.addWindowListener( new WindowAdapter() {
  115.         public void windowClosing(WindowEvent e) {System.exit(0);}});
  116.  
  117.     frame.pack();
  118.     frame.show();
  119.     }
  120.  
  121.     /** Constructs a JPanel containing check boxes for the different
  122.       * options that tree supports. */
  123.     private JPanel constructOptionsPanel() {
  124.     JCheckBox               aCheckbox;
  125.     JPanel           retPanel = new JPanel(false);
  126.     JPanel           borderPane = new JPanel(false);
  127.  
  128.     borderPane.setLayout(new BorderLayout());
  129.     retPanel.setLayout(new FlowLayout());
  130.  
  131.     aCheckbox = new JCheckBox("show handles");
  132.     aCheckbox.setSelected(tree.getShowsRootHandles());
  133.     aCheckbox.addChangeListener(new ShowHandlesChangeListener());
  134.     retPanel.add(aCheckbox);
  135.  
  136.     aCheckbox = new JCheckBox("show root");
  137.     aCheckbox.setSelected(tree.isRootVisible());
  138.     aCheckbox.addChangeListener(new ShowRootChangeListener());
  139.     retPanel.add(aCheckbox);
  140.  
  141.     aCheckbox = new JCheckBox("editable");
  142.     aCheckbox.setSelected(tree.isEditable());
  143.     aCheckbox.addChangeListener(new TreeEditableChangeListener());
  144.     aCheckbox.setToolTipText("Triple click to edit");
  145.     retPanel.add(aCheckbox);
  146.  
  147.     borderPane.add(retPanel, "North");
  148.  
  149.     /* Create a set of radio buttons that dictate what selection should
  150.        be allowed in the tree. */
  151.     ButtonGroup           group = new ButtonGroup();
  152.     JPanel         buttonPane = new JPanel(false);
  153.     JRadioButton          button;
  154.  
  155.     buttonPane.setLayout(new FlowLayout());
  156.     button = new JRadioButton("Single");
  157.     button.addActionListener(new AbstractAction() {
  158.         public boolean isEnabled() { return true; }
  159.         public void actionPerformed(ActionEvent e) {
  160.         tree.getSelectionModel().setSelectionMode
  161.             (TreeSelectionModel.SINGLE_TREE_SELECTION);
  162.         }
  163.     });
  164.     group.add(button);
  165.     buttonPane.add(button);
  166.     button = new JRadioButton("Contiguous");
  167.     button.addActionListener(new AbstractAction() {
  168.         public boolean isEnabled() { return true; }
  169.         public void actionPerformed(ActionEvent e) {
  170.         tree.getSelectionModel().setSelectionMode
  171.             (TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
  172.         }
  173.     });
  174.     group.add(button);
  175.     buttonPane.add(button);
  176.     button = new JRadioButton("Discontiguous");
  177.     button.addActionListener(new AbstractAction() {
  178.         public boolean isEnabled() { return true; }
  179.         public void actionPerformed(ActionEvent e) {
  180.         tree.getSelectionModel().setSelectionMode
  181.             (TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
  182.         }
  183.     });
  184.     button.setSelected(true);
  185.     group.add(button);
  186.     buttonPane.add(button);
  187.  
  188.     borderPane.add(buttonPane, "South");
  189.     return borderPane;
  190.     }
  191.  
  192.     /** Construct a menu. */
  193.     private JMenuBar constructMenuBar() {
  194.     JMenu            menu;
  195.     JMenuBar         menuBar = new JMenuBar();
  196.     JMenuItem        menuItem;
  197.  
  198.     /* Good ol exit. */
  199.     menu = new JMenu("File");
  200.     menuBar.add(menu);
  201.  
  202.     menuItem = menu.add(new JMenuItem("Exit"));
  203.     menuItem.addActionListener(new ActionListener() {
  204.         public void actionPerformed(ActionEvent e) {
  205.         System.exit(0);
  206.         }});
  207.  
  208.     /* Tree related stuff. */
  209.     menu = new JMenu("Tree");
  210.     menuBar.add(menu);
  211.  
  212.     menuItem = menu.add(new JMenuItem("Add"));
  213.     menuItem.addActionListener(new AddAction());
  214.  
  215.     menuItem = menu.add(new JMenuItem("Insert"));
  216.     menuItem.addActionListener(new InsertAction());
  217.  
  218.     menuItem = menu.add(new JMenuItem("Reload"));
  219.     menuItem.addActionListener(new ReloadAction());
  220.  
  221.     menuItem = menu.add(new JMenuItem("Remove"));
  222.     menuItem.addActionListener(new RemoveAction());
  223.  
  224.     return menuBar;
  225.     }
  226.  
  227.     /**
  228.       * Returns the TreeNode instance that is selected in the tree.
  229.       * If nothing is selected, null is returned.
  230.       */
  231.     protected DefaultMutableTreeNode getSelectedNode() {
  232.     TreePath   selPath = tree.getSelectionPath();
  233.  
  234.     if(selPath != null)
  235.         return (DefaultMutableTreeNode)selPath.getLastPathComponent();
  236.     return null;
  237.     }
  238.  
  239.     protected DefaultMutableTreeNode createNewNode(String name) {
  240.     return new DynamicTreeNode(new SampleData(null, Color.black, name));
  241.     }
  242.  
  243.     /**
  244.       * AddAction is used to add a new item after the selected item.
  245.       */
  246.     class AddAction extends Object implements ActionListener
  247.     {
  248.     /** Number of nodes that have been added. */
  249.     public int               addCount;
  250.  
  251.     /**
  252.       * Messaged when the user clicks on the Add menu item.
  253.       * Determines the selection from the Tree and adds an item
  254.       * after that.  If nothing is selected, an item is added to
  255.       * the root.
  256.       */
  257.     public void actionPerformed(ActionEvent e) {
  258.         int               newIndex;
  259.         DefaultMutableTreeNode          lastItem = getSelectedNode();
  260.         DefaultMutableTreeNode          parent;
  261.  
  262.         /* Determine where to create the new node. */
  263.         if(lastItem != null)
  264.         parent = (DefaultMutableTreeNode)lastItem.getParent();
  265.         else
  266.         parent = (DefaultMutableTreeNode)treeModel.getRoot();
  267.         if(lastItem == null)
  268.         newIndex = treeModel.getChildCount(parent);
  269.         else
  270.         newIndex = parent.getIndex(lastItem) + 1;
  271.  
  272.         /* Let the treemodel know. */
  273.         treeModel.insertNodeInto(createNewNode("Added " +
  274.                     Integer.toString(addCount++)),
  275.                      parent, newIndex);
  276.     }
  277.     } // End of SampleTree.AddAction
  278.  
  279.  
  280.     /**
  281.       * InsertAction is used to insert a new item before the selected item.
  282.       */
  283.     class InsertAction extends Object implements ActionListener
  284.     {
  285.     /** Number of nodes that have been added. */
  286.     public int               insertCount;
  287.  
  288.     /**
  289.       * Messaged when the user clicks on the Insert menu item.
  290.       * Determines the selection from the Tree and inserts an item
  291.       * after that.  If nothing is selected, an item is added to
  292.       * the root.
  293.       */
  294.     public void actionPerformed(ActionEvent e) {
  295.         int               newIndex;
  296.         DefaultMutableTreeNode          lastItem = getSelectedNode();
  297.         DefaultMutableTreeNode          parent;
  298.  
  299.         /* Determine where to create the new node. */
  300.         if(lastItem != null)
  301.         parent = (DefaultMutableTreeNode)lastItem.getParent();
  302.         else
  303.         parent = (DefaultMutableTreeNode)treeModel.getRoot();
  304.         if(lastItem == null)
  305.         newIndex = treeModel.getChildCount(parent);
  306.         else
  307.         newIndex = parent.getIndex(lastItem);
  308.  
  309.         /* Let the treemodel know. */
  310.         treeModel.insertNodeInto(createNewNode("Inserted " +
  311.                     Integer.toString(insertCount++)),
  312.                      parent, newIndex);
  313.     }
  314.     } // End of SampleTree.InsertAction
  315.  
  316.  
  317.     /**
  318.       * ReloadAction is used to reload from the selected node.  If nothing
  319.       * is selected, reload is not issued.
  320.       */
  321.     class ReloadAction extends Object implements ActionListener
  322.     {
  323.     /**
  324.       * Messaged when the user clicks on the Reload menu item.
  325.       * Determines the selection from the Tree and asks the treemodel
  326.       * to reload from that node.
  327.       */
  328.     public void actionPerformed(ActionEvent e) {
  329.         DefaultMutableTreeNode          lastItem = getSelectedNode();
  330.  
  331.         if(lastItem != null)
  332.         treeModel.reload(lastItem);
  333.     }
  334.     } // End of SampleTree.ReloadAction
  335.  
  336.     /**
  337.       * RemoveAction removes the selected node from the tree.  If
  338.       * The root or nothing is selected nothing is removed.
  339.       */
  340.     class RemoveAction extends Object implements ActionListener
  341.     {
  342.     /**
  343.       * Removes the selected item as long as it isn't root.
  344.       */
  345.     public void actionPerformed(ActionEvent e) {
  346.         DefaultMutableTreeNode          lastItem = getSelectedNode();
  347.  
  348.         if(lastItem != null && lastItem != (DefaultMutableTreeNode)treeModel.getRoot()) {
  349.         treeModel.removeNodeFromParent(lastItem);
  350.         }
  351.     }
  352.     } // End of SampleTree.RemoveAction
  353.  
  354.  
  355.     /**
  356.       * ShowHandlesChangeListener implements the ChangeListener interface
  357.       * to toggle the state of showing the handles in the tree.
  358.       */
  359.     class ShowHandlesChangeListener extends Object implements ChangeListener
  360.     {
  361.     public void stateChanged(ChangeEvent e) {
  362.         tree.setShowsRootHandles(((JCheckBox)e.getSource()).isSelected());
  363.     }
  364.  
  365.     } // End of class SampleTree.ShowHandlesChangeListener
  366.  
  367.  
  368.     /**
  369.       * ShowRootChangeListener implements the ChangeListener interface
  370.       * to toggle the state of showing the root node in the tree.
  371.       */
  372.     class ShowRootChangeListener extends Object implements ChangeListener
  373.     {
  374.     public void stateChanged(ChangeEvent e) {
  375.         tree.setRootVisible(((JCheckBox)e.getSource()).isSelected());
  376.     }
  377.  
  378.     } // End of class SampleTree.ShowRootChangeListener
  379.  
  380.  
  381.     /**
  382.       * TreeEditableChangeListener implements the ChangeListener interface
  383.       * to toggle between allowing editing and now allowing editing in
  384.       * the tree.
  385.       */
  386.     class TreeEditableChangeListener extends Object implements ChangeListener
  387.     {
  388.     public void stateChanged(ChangeEvent e) {
  389.         tree.setEditable(((JCheckBox)e.getSource()).isSelected());
  390.     }
  391.  
  392.     } // End of class SampleTree.TreeEditableChangeListener
  393.  
  394.  
  395.     static public void main(String args[]) {
  396.     new SampleTree();
  397.     }
  398.  
  399. }
  400.